﻿using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;

namespace OMG.Fill.Potato.UI
{
    public class ApiActionException : ExceptionFilterAttribute
    {
        //重写基类的异常处理方法
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //1.异常日志记录（正式项目里面一般是用log4net记录异常日志）
            LogHelper.ErrorLog("控制器错误信息", actionExecutedContext.Exception);
            //2.返回调用方具体的异常信息
            if (actionExecutedContext.Exception is NotImplementedException)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                response.Content = new StringContent("方法不被支持");
                response.ReasonPhrase = "This Func is Not Supported";
                response.StatusCode = HttpStatusCode.NotImplemented;
                actionExecutedContext.Response = response;
            }
            else if (actionExecutedContext.Exception is TimeoutException)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
                response.Content = new StringContent("客户端没有在服务器期望请求的时间内发送请求");
                response.ReasonPhrase = "This Func is Request Timeout";
                actionExecutedContext.Response = response;
            }
            else if (actionExecutedContext.Exception is TimeoutException)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                response.Content = new StringContent("您没权访问该接口");
                response.ReasonPhrase = "This Func is Unauthorized";
                actionExecutedContext.Response = response;
            }
            //.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常，统一返回服务端错误500
            else
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            base.OnException(actionExecutedContext);
        }
    }
    #region 重写文件上传方法
    public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public ReNameMultipartFormDataStreamProvider(string root)
            : base(root)
        { }
        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            //截取文件扩展名
            string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'));
            string name = base.GetLocalFileName(headers).Replace("_", "").Replace("-", "");
            return name + exp;
        }
    }
    #endregion
}